package com.pwt.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pwt.entity.Role;
import com.pwt.entity.User;
import com.pwt.model.RoleDoorModel;
import com.pwt.repository.RoleRepository;
import com.pwt.repository.UserRepository;
import com.pwt.repository.UserRoleRepository;
import com.pwt.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import nonapi.io.github.classgraph.utils.LogNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author dw
 * @date 2022/1/24 10:39
 * @Description
 */
@Component
@Slf4j
public class UserScheduled {

    private UserRoleRepository userRoleRepository;

    private UserRepository userRepository;

    private RoleRepository roleRepository;

    @Value("${accountToken.username}")
    private String username;

    @Value("${accountToken.password}")
    private String password;

    @Value("${accountToken.systemCode}")
    private String systemCode;

    @Value("${accountToken.ip}")
    private String ip;

    private String tokenId;

    public UserScheduled(UserRoleRepository userRoleRepository, UserRepository userRepository, RoleRepository roleRepository) {
        this.userRoleRepository = userRoleRepository;
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    public void updateUserInformation(){
//        获取token  验证服务  post   body
//        http://IP:port/seeyon/rest/token/
//        获取所有单位信息
//        http://ip:port/seeyon/rest/orgAccounts
//        根据单位获取部门信息
//        http请求方式：GET
//        http://ip:port/seeyon/rest/orgDepartments/all/{accountId}
//        根据单位获取人员信息
//        http请求方式：GET
//        http://ip:port/seeyon/rest/orgMembers/all/{accountId}
//        systemCode : oqm    memberCode : 人员编号
//        http://ip:port/seeyon/rest/thirdparty/role
        //获取token
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("userName",username);
        tokenMap.put("password",password);
        String token = HttpUtils.doPost("http://"+ip+"/seeyon/rest/token/",tokenMap);
        if(StringUtils.isBlank(token)){
            log.error("同步用户： 获取token失败！");
            return;
        }
        JSONObject tokenObj = JSONObject.parseObject(token);
        tokenId = tokenObj.getString("id");
        //header添加token
        Map<String,Object> header = new HashMap<>();
        header.put("token",tokenId);

        //获取集团对象
        String orgAccount = HttpUtils.doGet("http://"+ip+"/seeyon/rest/orgAccounts",header,null);
        if(StringUtils.isBlank(orgAccount)){
            log.error("同步用户： 获取集团接口请求失败！");
            return;
        }
        JSONArray orgAccountArray = JSONArray.parseArray(orgAccount);
        for (int i = 0; i < orgAccountArray.size(); i++) {
            JSONObject account = orgAccountArray.getJSONObject(i);
            if(account == null) continue;
            //单位id
            String orgAccountId = account.getString("id");
            //获取单位下所有人员
            String orgMembers = HttpUtils.doGet("http://"+ip+"/seeyon/rest/orgMembers/all/"+orgAccountId,header,null);
            if(StringUtils.isBlank(orgMembers)){
                log.error("同步用户： 根据集团id获取集团人员请求失败！");
                return;
            }
            JSONArray orgMembersArray = JSONArray.parseArray(orgMembers);
            for (int j = 0; j < orgMembersArray.size(); j++) {
                //用户对象
                JSONObject members = orgMembersArray.getJSONObject(j);
                String loginName = members.getString("loginName");
                String code = members.getString("code");
                if(StringUtils.isBlank(code)) continue;
                //根据人员编码 查询人员异构系统角色服务   普通用户和管理员，0000和0001
                String role = HttpUtils.doGet("http://"+ip+"/seeyon/rest/thirdparty/role/"+systemCode+"/"+code);
                if(StringUtils.isBlank(role)) continue;
                JSONObject roleJson = JSONObject.parseObject(role);
                //人员初始角色信息
                String roleData = roleJson.getString("data");
                if(StringUtils.isBlank(roleData)) continue;
                List<RoleDoorModel> roleArray = JSONArray.parseArray(roleData, RoleDoorModel.class);
                List<String> roleIds = new ArrayList<>();
                for (RoleDoorModel roleDoor:roleArray) {
                   String roleCode  = roleDoor.getRoleCode().substring(roleDoor.getRoleCode().length()-4,roleDoor.getRoleCode().length());
                    Role roleBySign = null;
                   if(roleCode.equals("0000")){
                       roleBySign = this.roleRepository.findBySign("root");
                   }else if(roleCode.equals("0001")){
                       roleBySign = this.roleRepository.findBySign("user");
                   }
                    if(roleBySign != null && roleBySign.getId() != null) roleIds.add(roleBySign.getId());
                }
                if(roleIds == null || roleIds.size() < 1) continue;


                if(StringUtils.isBlank(loginName)) continue;
                User user = this.userRepository.findByUsername(loginName);
                if(user == null){
                    user = new User();
                }
                //人员编码
                if(StringUtils.isNotBlank(code)) user.setCode(code);
                //姓名
                if(StringUtils.isNotBlank(members.getString("name"))) user.setNickName(members.getString("name"));
                //单位id
                if(StringUtils.isNotBlank(members.getString("orgAccountId"))) user.setOrgAccountId(members.getString("orgAccountId"));
                //单位名称
                if(StringUtils.isNotBlank(members.getString("orgAccountName"))) user.setOrgAccountName(members.getString("orgAccountName"));
                //部门id
                if(StringUtils.isNotBlank(members.getString("orgDepartmentId"))) user.setOrgDepartmentId(members.getString("orgDepartmentId"));
                //部门名称
                if(StringUtils.isNotBlank(members.getString("orgDepartmentName"))) user.setOrgDepartmentName(members.getString("orgDepartmentName"));
                //职位id
                if(StringUtils.isNotBlank(members.getString("orgPostId"))) user.setOrgPostId(members.getString("orgPostId"));
                //职位名称
                if(StringUtils.isNotBlank(members.getString("orgPostName"))) user.setOrgPostName(members.getString("orgPostName"));
                User userVo = this.userRepository.save(user);

                for (String roleId : roleIds) {
                    roleRepository.saveUserRole(userVo.getId(), roleId, UUID.randomUUID().toString().replaceAll("-", ""));
                }

            }

        }

    }
}
